from backend.cews.models import Parts, TrainborneMaintenanceRecords, RepairOrderPart
from datetime import datetime
from django.db.models import Q
import re

def record_history(stock_code, serial_no, status):
    def check_date_format(date_string, date_format):
        pattern = re.compile(date_format)
        return pattern.match(date_string) is not None
    
    query = Q()
    
    if status:
        query.add(Q(status__in=status), Q.AND)

    results = []

    date_format = r'\d{4}-\d{2}-\d{2}'

    part = Parts.objects.get(stock_code=stock_code, serial_no=serial_no, deleted=False)
    rops = RepairOrderPart.objects.select_related("repair_order").order_by('-id').filter(stock_code=stock_code, serial_no=serial_no, deleted=False).filter(query)[0:5]

    old_records = TrainborneMaintenanceRecords.objects.filter(stock_code=stock_code, serial_no=serial_no)[0:5]
    
    for rop in rops:
       
        data = {}
        data['stock_code'] = rop.stock_code
        data['description'] = rop.description
        data['serial_no'] = rop.serial_no
        data['order_id'] = rop.repair_order.id
        data['check_in'] = rop.repair_order.check_in.strftime('%Y-%m-%d %H:%M:%S')

        if rop.repair_order.check_out is None:
            data['check_out'] = None
        else:
            data['check_out'] = rop.repair_order.check_out.strftime('%Y-%m-%d %H:%M:%S')
            
        data['order_no'] = rop.repair_order.order_no
        data['status'] = rop.repair_order.status
        results.append(data)

    for old_record in old_records:
        data = {}
        # if old_record.receive_date.lower() == 'nil':
        #     data['check_in'] = old_record.receive_date.lower()
        # else:
        #     data['check_in'] =  datetime.strptime(old_record.receive_date + ' 00:00:00', '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')

        # if old_record.out_date.lower() == 'nil':
        #     data['check_out'] = old_record.out_date.lower()
        # else:
        #     data['check_out'] = datetime.strptime( old_record.out_date+ ' 00:00:00', '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
        if old_record.receive_date.lower() == 'nil' or old_record.out_date.lower() == 'nil':
            continue
        data['stock_code'] = old_record.stock_code
        data['description'] = old_record.equipment
        data['main_record_id'] = old_record.id
        data['status'] = old_record.finding
        data['check_in'] =  datetime.strptime(old_record.receive_date + ' 00:00:00', '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
        data['check_out'] = datetime.strptime( old_record.out_date+ ' 00:00:00', '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
        results.append(data)
    
    sorted_data = sorted(results, key=lambda x: x['check_in'], reverse=True)  

    return sorted_data[0:5]

    # return TrainborneMaintenanceRecords.objects.filter(equipment=part.lv5, serial_no=part.serial_no)[0:5]


def get_record(main_record_id):

    return TrainborneMaintenanceRecords.objects.get(pk=main_record_id)

# def get_part(equipment, serial_no):
    
#     part = Parts.objects.get(description__icontains=equipment, serial_no=serial_no, deleted=False)
    
#     return part